#target photoshop

if (typeof JSON === "undefined") {
    JSON = {};
    JSON.stringify = function (obj) {
        if (typeof obj !== "object" || obj === null) return String(obj);
        var json = [], isArray = obj && obj.constructor === Array;
        for (var key in obj) {
            var value = obj[key];
            var str = typeof value === "string" ? '"' + value + '"' : JSON.stringify(value);
            json.push((isArray ? "" : '"' + key + '":') + str);
        }
        return (isArray ? "[" : "{") + json.join(",") + (isArray ? "]" : "}");
    };
}

// 选择包含 PSD 文件的文件夹
var psdFolder = new Folder("D:\\项目资源\\Z找不同\\微信找不同");
var scriptFile = new File($.fileName);         // 当前脚本完整路径
var scriptFolder = scriptFile.parent;          // 当前脚本所在目录（Folder 对象）

var outputDir = scriptFile.parent
var levelResArray = [
    'A086'
]

function arrayIndexOf(arr, val) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === val) return i;
    }
    return -1;
}

// 获取所有 PSD 文件
var psdFiles = psdFolder.getFiles(function (f) {
    return f instanceof File && f.name.match(/\.psd$/i);
});

if (psdFiles.length === 0) {
    alert("未找到任何 PSD 文件。");
    exit();
}
function renameLayers(doc, fileNameNoExt) {
    var layers = doc.layers;
    for (var i = 0; i < layers.length - 1; i++)  //-1是不要底图
    {
        var layer = layers[i];
        layer.name = fileNameNoExt + "_" + i;
    }
}

function exportJson(doc, fileNameNoExt) {
    //生成配置

    var fileOut = new File(outputDir + "\\" + fileNameNoExt + ".json");
    //设置文件的操作模式为写入模式。
    fileOut.open("w", "TEXT", "????");

    var str = '{\r\n';
    var layers = doc.layers;
    var width = doc.width;
    var h = doc.height;
    for (var i = 0; i < layers.length - 1; i++)  //-1是不要底图
    {
        var layer = layers[i];
        str += '  "' + layer.name + '":';
        var bounds = layer.bounds;

        str = str + ' {"x":' + parseInt(bounds[0] - width * 0.5 + (bounds[2] - bounds[0]) * 0.5)
            + ',"y":' + parseInt(h * 0.5 - bounds[1] - (bounds[3] - bounds[1]) * 0.5)
            + ',"w":' + parseInt(bounds[2] - bounds[0])
            + ',"h":' + parseInt(bounds[3] - bounds[1]);
        if (i == layers.length - 2) {
            str = str + '}\r\n';
        } else {
            str = str + '},\r\n';
        }

    }
    str += ',"allinone":1'
    str += '}';
    fileOut.write(str);
    //文件写入成功后，关闭文件的输入流。
    fileOut.close();
}

function SavePNG(doc, saveFilePath) {
    var tempDoc = doc.duplicate();
    var pngOpts = new ExportOptionsSaveForWeb;
    pngOpts.format = SaveDocumentType.PNG
    pngOpts.PNG8 = false;
    pngOpts.transparency = true;
    pngOpts.interlaced = false;
    pngOpts.quality = 100;

    var allLayers = tempDoc.artLayers;
    // 显示背景图层
    if (allLayers.length > 0) {
        allLayers[allLayers.length - 1].visible = true;
    }
    // 隐藏其他图层
    for (var i = 0; i < allLayers.length - 1; i++) {
        allLayers[i].visible = false;
    }
    
    tempDoc.exportDocument(new File(outputDir + "\\" + saveFilePath + ".png"), ExportType.SAVEFORWEB, pngOpts);

    // 隐藏背景图层
    if (allLayers.length > 0) {
        allLayers[allLayers.length - 1].visible = false;
    }
    // 显示其他图层
    for (var i = 0; i < allLayers.length - 1; i++) {
        allLayers[i].visible = true;
    }
    tempDoc.mergeVisibleLayers();
    tempDoc.exportDocument(new File(outputDir + "\\" + saveFilePath + "_b.png"), ExportType.SAVEFORWEB, pngOpts);

    tempDoc.close(SaveOptions.DONOTSAVECHANGES);
}

for (var f = 0; f < psdFiles.length; f++) {
    var psdFile = psdFiles[f];
    var psdFileNoExt = psdFile.name.replace(/\.psd$/i, "");
    var idx = arrayIndexOf(levelResArray, psdFileNoExt);
    // alert("正在处理文件: " + psdFileNoExt + " idx:"+idx);
    if (idx == -1)
        continue;
    levelResArray.splice(idx, 1)
    var doc = app.open(psdFile);

    renameLayers(doc, psdFileNoExt);
    exportJson(doc, psdFileNoExt);

    // 保存所有图层状态
    var allLayers = doc.artLayers;
    var savedStates = [];
    for (var i = 0; i < allLayers.length; i++) {
        savedStates.push({
            visible: allLayers[i].visible,
            allLocked: allLayers[i].allLocked
        });
    }


    // if (doc.backgroundLayer != undefined) {
    //     doc.backgroundLayer.visible = false;
    // } else {
    //     for (var i = 0; i < allLayers.length; i++) {
    //         var name_ = allLayers[i].name.toLowerCase();
    //         if (name_ === "background" || name_ === "背景") {
    //             allLayers[i].visible = false;
    //             break;
    //         }
    //     }
    // }



    // 合并并导出
    // var tempDoc = doc.duplicate();
    // tempDoc.mergeVisibleLayers();

    var outputName = psdFile.name.replace(/\.psd$/i, "_b.png");
    // var pngFile = new File(outputDir + "/" + outputName);
    // var pngOptions = new PNGSaveOptions();
    // tempDoc.saveAs(pngFile, pngOptions, true, Extension.LOWERCASE);
    // tempDoc.close(SaveOptions.DONOTSAVECHANGES);

    SavePNG(doc, psdFileNoExt)


    // 恢复图层状态
    for (var i = 0; i < allLayers.length; i++) {
        allLayers[i].visible = savedStates[i].visible;
        allLayers[i].allLocked = savedStates[i].allLocked;
    }

    doc.close(SaveOptions.DONOTSAVECHANGES);
}

alert("批量导出完成！剩余:", JSON.stringify(levelResArray));
